package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.schedule.IScheduleClient;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.TaskTypeEnum;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Hashtable;

/**
 * 用于对接延迟任务模块
 */
@Service
@Slf4j
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    IScheduleClient iScheduleClient;
    @Autowired
    WmNewsAutoScanService wmNewsAutoScanService;

    @Override
    public void addNewsToTask(WmNews wmNews) {
        log.info("发布文章时，调用延迟任务模块 添加任务 {}", wmNews);
        Task task = new Task();
        task.setExecuteTime(wmNews.getPublishTime().getTime());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
//        task.setParameters(JSON.toJSONString(wmNews).getBytes(StandardCharsets.UTF_8));

        //JSON.toJSONString(wmNews).getBytes(); 性能大小会有问题
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        iScheduleClient.addTask(task);
    }


    /**
     * 每秒拉取一次任务  用于审核文章
     */
    @Scheduled(cron = "* * * * * ?")
    public void pullNewsTask(){
        log.info("拉取任务，用于审核文章");
        ResponseResult responseResult = iScheduleClient.pull(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType(), TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        if(responseResult!=null && responseResult.getCode().equals(200) && responseResult.getData()!=null){
            log.info("拉取任务，拉取到了  {}", JSON.toJSONString(responseResult.getData()));
            Task task = JSON.parseObject(JSON.toJSONString(responseResult.getData()), Task.class);
            WmNews wmNews = ProtostuffUtil.deserialize(task.getParameters(), WmNews.class);

            //从延迟任务模块拉取到文章，说明该文章到时间了，需要审核发布
            wmNewsAutoScanService.autoScanWnNews(wmNews.getId());
        }
    }

    public static void main(String[] args) {
        HashMap map = new HashMap<>();
        map.put(null, "lisi");
        map.put(null, "wangwu");
        System.out.println(map.get(null));

        Hashtable<Object, Object> objectObjectHashtable = new Hashtable<>();
        objectObjectHashtable.put(null,"zhangsan");
        System.out.println(objectObjectHashtable);
    }
}
